package com.fengye.redisson.demo.message;

import com.fengye.redisson.demo.dto.MessageDTO;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RTopic;
import org.redisson.api.RedissonClient;
import org.redisson.api.listener.MessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

/**
 *
 * @author sky
 * @date 2021年06月16日 10:39 上午
 */
@Component
@Slf4j
public class MsgSubscriber implements ApplicationRunner, Ordered {
    static final String topicName = "REDISSON_TOPIC";

    @Autowired
    private RedissonClient redissonClient;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        try {
            RTopic topic = redissonClient.getTopic(topicName);
            topic.addListener(MessageDTO.class, new MessageListener<MessageDTO>() {
                @Override
                public void onMessage(CharSequence charSequence, MessageDTO messageDTO) {
                    log.info("收到消息,主题为{},消息内容为:{}", charSequence, messageDTO);
                }
            });
        } catch (Exception e) {
            log.error("异常", e.fillInStackTrace());
            throw e;
        }
    }

    /**
     * 项目启动时也随之启动
     * @return int
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
